package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.misc.DbUtils;
import com.mai4j.maiadmin.model.dto.LocationDTO;
import com.mai4j.maiadmin.model.dto.PageDTO;
import com.mai4j.maiadmin.model.http.datatables.Datatable;
import com.mai4j.maiadmin.model.http.datatables.Search;
import com.mai4j.maiadmin.service.LocationDescriptionService;
import com.mai4j.maiadmin.service.LocationService;
import com.mai4j.maiadmin.service.QueryService;
import com.mai4j.maiadmin.support.IdProvider;
import com.mai4j.maiadmin.support.JooqProvider;
import com.mai4j.maiadmin.support.cache.CacheName;
import org.apache.commons.lang3.StringUtils;
import org.jooq.*;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.mai4j.maiadmin.generated.Tables.LOCATION;
import static com.mai4j.maiadmin.generated.Tables.LOCATION_DESCRIPTION;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class LocationServiceImpl implements LocationService {

    private final LocationDescriptionService locationDescriptionService;

    private final QueryService queryService;

    public LocationServiceImpl(LocationDescriptionService locationDescriptionService, QueryService queryService) {
        this.locationDescriptionService = locationDescriptionService;
        this.queryService = queryService;
    }

    @Cacheable(value = CacheName.DATA, key = "'location:' + #locationId")
    @Override
    public LocationDTO get(Long locationId) {
        return JooqProvider.dsl()
                .select(LOCATION.asterisk())
                .from(LOCATION)
                .where(LOCATION.LOCATION_ID.eq(locationId))
                .fetchOne(recordLocationDTORecordMapper());
    }

    @Override
    public PageDTO<LocationDTO> paginate(Datatable datatable) {
        DSLContext dsl = JooqProvider.dsl();
        SelectJoinStep<Record> query = dsl.select(LOCATION.asterisk()).from(LOCATION);
        String value = Optional.ofNullable(datatable.getSearch()).orElse(new Search()).getValue();
        List<Condition> conditions = new ArrayList<>();
        if (StringUtils.isNotBlank(value)) {
            value = "%" + value + "%";
            conditions.add(
                    LOCATION.CODE.like(value)
                            .or(LOCATION.LOCATION_ID.in(
                                    dsl.select(LOCATION_DESCRIPTION.LOCATION_ID)
                                            .from(LOCATION_DESCRIPTION)
                                            .where(LOCATION_DESCRIPTION.NAME.like(value)))));
        }
        query.where(conditions);
        int count = queryService.fetchCount(query).count;
        List<LocationDTO> locationDTOS = count == 0 ? new ArrayList<>() : query
                .orderBy(LOCATION.SORT_ORDER)
                .limit(datatable.getStart(), datatable.getLength())
                .fetch(recordLocationDTORecordMapper());
        return new PageDTO<>(locationDTOS, DbUtils.getPage(datatable), datatable.getLength(), DbUtils.getTotalPage(count, datatable), count);
    }

    @Transactional
    @CacheEvict(value = CacheName.DATA,
            key = "'location:' + #locationDTO.getLocationId()",
            condition = "#locationDTO.getLocationId() != null")
    @Override
    public LocationDTO saveOrUpdate(LocationDTO locationDTO) {
        DSLContext dsl = JooqProvider.dsl();
        int count = dsl.fetchCount(dsl.selectFrom(LOCATION).where(LOCATION.LOCATION_ID.eq(locationDTO.getLocationId())));
        long locationId = count == 0 ? IdProvider.next() : locationDTO.getLocationId();
        if (count == 0) {
            dsl.insertInto(LOCATION)
                    .columns(LOCATION.LOCATION_ID,
                            LOCATION.CODE,
                            LOCATION.SORT_ORDER,
                            LOCATION.STATUS,
                            LOCATION.DATE_ADDED,
                            LOCATION.DATE_MODIFIED)
                    .values(locationId,
                            locationDTO.getCode(),
                            locationDTO.getSortOrder(),
                            locationDTO.getStatus(),
                            LocalDateTime.now(),
                            LocalDateTime.now()).execute();
        } else {
            dsl.update(LOCATION)
                    .set(LOCATION.CODE, locationDTO.getCode())
                    .set(LOCATION.SORT_ORDER, locationDTO.getSortOrder())
                    .set(LOCATION.STATUS, locationDTO.getStatus())
                    .set(LOCATION.DATE_MODIFIED, LocalDateTime.now())
                    .where(LOCATION.LOCATION_ID.eq(locationId))
                    .execute();
        }
        locationDescriptionService.saveDescriptions(locationId, locationDTO.getDescriptions());
        return get(locationId);
    }

    @CacheEvict(value = CacheName.DATA, key = "'location:' + #locationId")
    @Transactional
    @Override
    public void delete(Long locationId) {
        JooqProvider.dsl()
                .deleteFrom(LOCATION)
                .where(LOCATION.LOCATION_ID.eq(locationId))
                .execute();
        locationDescriptionService.delete(locationId);
    }

    /**
     * RecordCurrencyDTORecordMapper
     *
     * @return RecordMapper
     */
    private RecordMapper<Record, LocationDTO> recordLocationDTORecordMapper() {
        return record -> {
            LocationDTO locationDTO = record.into(LocationDTO.class);
            locationDTO.setDescriptions(locationDescriptionService.get(locationDTO.getLocationId()));
            return locationDTO;
        };
    }
}
